<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getAnimeList, addAnime, updateAnime, deleteAnime, uploadAnimeImage } from '@/apis/anime'
import { getCategoryList } from '@/apis/category'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(4)
const loading = ref(false)

// 搜索相关
const searchName = ref('')
const searchStatus = ref('')
const statusOptions = [
  { label: '连载', value: '连载' },
  { label: '完结', value: '完结' },
  { label: '未上映', value: '未上映' }
]
const searchCategoryIds = ref([])

// 分类下拉
const categoryOptions = ref([])
const fetchCategoryOptions = async () => {
  const res = await getCategoryList({ page: 1, pageSize: 1000 })
  if (res.code === 1 && res.data) {
    categoryOptions.value = res.data.list || []
  }
}

// 获取动漫列表
const fetchList = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      name: searchName.value,
      status: searchStatus.value
    }
    if (searchCategoryIds.value && searchCategoryIds.value.length) {
      params.categoryIds = searchCategoryIds.value.join(',')
    }
    const res = await getAnimeList(params)
    if (res.code === 1 && res.data) {
      list.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      list.value = []
      total.value = 0
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchCategoryOptions()
  fetchList()
})

// 时间格式化
function formatDate(val) {
  if (!val) return ''
  const d = new Date(val)
  return d.toLocaleString()
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add/edit
const form = reactive({ id: '', name: '', categoryIds: [], status: '', imageUrl: '', year: '', rating: '', description: '' })
const formRef = ref(null)
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  categoryIds: [{ required: true, message: '请选择分类', trigger: 'change' }],
  status: [{ required: true, message: '请输入状态', trigger: 'blur' }],
  year: [{ required: true, message: '请输入年份', trigger: 'blur' }],
  rating: [{ required: true, message: '请输入评分', trigger: 'blur' }],
  description: [{ required: true, message: '请输入简介', trigger: 'blur' }]
}

// 上传图片相关（自定义 http-request）
const customUpload = async (option) => {
  const formData = new FormData()
  formData.append('file', option.file)
  try {
    const res = await uploadAnimeImage(formData)
    if (res.code === 1 && res.data && res.data.url) {
      form.imageUrl = res.data.url
      ElMessage.success('图片上传成功')
      option.onSuccess(res, option.file)
    } else {
      ElMessage.error(res.msg || '图片上传失败')
      option.onError(new Error(res.msg || '上传失败'))
    }
  } catch (e) {
    ElMessage.error('图片上传异常')
    option.onError(e)
  }
}
const beforeUpload = (file) => {
  // 可加图片类型/大小校验
  return true
}

const onAdd = () => {
  dialogType.value = 'add'
  form.id = ''
  form.name = ''
  form.categoryIds = []
  form.status = ''
  form.imageUrl = ''
  form.year = ''
  form.rating = ''
  form.description = ''
  dialogVisible.value = true
}
const onEdit = (row) => {
  dialogType.value = 'edit'
  form.id = row.id
  form.name = row.name
  form.categoryIds = Array.isArray(row.categoryIds) ? row.categoryIds : (row.categoryIds ? [row.categoryIds] : [])
  form.status = row.status
  form.imageUrl = row.imageUrl || ''
  form.year = row.year || ''
  form.rating = row.rating || ''
  form.description = row.description || ''
  dialogVisible.value = true
}
const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    if (dialogType.value === 'add') {
      const res = await addAnime(form)
      if (res.code === 1) {
        ElMessage.success('新增成功')
        dialogVisible.value = false
        fetchList()
      }
    } else {
      const res = await updateAnime(form)
      if (res.code === 1) {
        ElMessage.success('编辑成功')
        dialogVisible.value = false
        fetchList()
      }
    }
  })
}
const onDelete = (row) => {
  ElMessageBox.confirm('确定要删除该动漫吗？', '提示', { type: 'warning' })
    .then(async () => {
      const res = await deleteAnime({ id: row.id })
      if (res.code === 1) {
        ElMessage.success('删除成功')
        fetchList()
      }
    })
}
</script>
<template>
  <div>
    <h2>动漫管理</h2>
    <div class="anime-header">
      <el-input v-model="searchName" placeholder="搜索名称" style="width: 180px; margin-right: 12px;" @keyup.enter="fetchList" />
      <el-select v-model="searchCategoryIds" placeholder="搜索分类" clearable multiple style="width: 200px; margin-right: 12px;">
        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="searchStatus" placeholder="搜索状态" clearable style="width: 120px; margin-right: 12px;">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="primary" @click="fetchList" style="margin-right: 12px;">搜索</el-button>
      <el-button type="primary" @click="onAdd">新增动漫</el-button>
    </div>
    <el-table :data="list" v-loading="loading" border style="width: 100%; margin-top: 16px;">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="名称" />
      <el-table-column label="图片" width="100">
        <template #default="scope">
          <el-image v-if="scope.row.imageUrl" :src="scope.row.imageUrl" style="width: 60px; height: 60px; object-fit: cover;" :preview-src-list="[scope.row.imageUrl]" preview-teleported />
        </template>
      </el-table-column>
      <el-table-column label="分类">
        <template #default="scope">
          <span v-if="Array.isArray(scope.row.categoryIds)">
            {{ scope.row.categoryIds.map(cid => (categoryOptions.find(c => c.id === cid) ? categoryOptions.find(c => c.id === cid).name : cid)).join('，') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" />
      <el-table-column prop="year" label="年份" width="100" />
      <el-table-column prop="rating" label="评分" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="scope">{{ formatDate(scope.row.updateTime) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="onEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next, jumper"
      style="margin-top: 16px; text-align: right;"
      @current-change="fetchList"
      @size-change="fetchList"
    />
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增动漫' : '编辑动漫'">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            :http-request="customUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar-large-vertical" />
            <el-icon v-else style="font-size: 64px;"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类" prop="categoryIds">
          <el-select v-model="form.categoryIds" placeholder="请选择分类" multiple>
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-input v-model="form.year" placeholder="请输入年份" />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-input v-model="form.rating" placeholder="请输入评分" />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入简介" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.anime-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 180px;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-large-vertical {
  width: 180px;
  height: 240px;
  display: block;
  object-fit: cover;
  border-radius: 8px;
  background: #fff;
}
/* 新增：让主容器背景透明 */
:deep(.el-table),
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table th),
:deep(.el-table td),
:deep(.el-table__cell),
:deep(.el-table__row) {
  background: rgba(255, 255, 255, 0.2) !important;
}
:deep(.el-table) {
  background: rgba(255,255,255,0.2) !important;
  border-radius: 16px !important;
  overflow: hidden;
}

:deep(.el-table__header),
:deep(.el-table__header th),
:deep(.el-table thead),
:deep(.el-table thead tr),
:deep(.el-table thead th) {
  background: rgba(255, 255, 255, 0.2) !important;
}

:deep(.el-dialog),
:deep(.el-dialog__body) {
  background: rgb(255, 255, 255) !important;
  border-radius: 0 !important;
}

:deep(.el-pagination) {
  background: rgba(255, 255, 255, 0) !important;
  border-radius: 8px !important;
}

:deep(.el-pager li) {
  background: rgba(255, 255, 255, 0.5) !important;
  border-radius: 6px !important;
}

/* 页面主容器透明 */
div:has(> .anime-header) {
  background: transparent !important;
  box-shadow: none !important;
}
</style>
